package com.adwin.addcoin

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import com.adwin.addcoin.repository.Repost.BurialSiteRepostUtils
import com.adwin.addcoin.utils.DevicesUtils
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.TaskStatusNet
import com.adwin.addcoin.utils.dataStore
import com.adwin.addcoin.utils.getAgreement
import com.adwin.addcoin.utils.getDevicesId
import com.adwin.addcoin.utils.saveDevicesId
import com.appsflyer.AppsFlyerConversionListener
import com.appsflyer.AppsFlyerLib
import com.appsflyer.attribution.AppsFlyerRequestListener
import com.cashbird.app.infra.utils.FlowBus
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class AddCoinApplication : Application(), LifecycleEventObserver {
    companion object {
        lateinit var instance: AddCoinApplication
        var url = ""
        var gaid = ""
        var token = ""
        var isCloak = true
        fun myLog(log: Any?) {
            if (!BuildConfig.DEBUG) {
                return
            }
            try {
                val name = Throwable().stackTrace[1].methodName
                println("===>$name,$log")
            } catch (e: Exception) {
                e.printStackTrace()
                println("===>$log")
            }
        }
    }

    var isGuestLogin = false

   var activityDd:Activity? = null
//测试提交
    val time = object : CountDownTimer(Long.MAX_VALUE,1000){

        override fun onFinish() {

        }

        override fun onTick(millisUntilFinished: Long) {
            val isbacg = BurialSiteRepostUtils.isBackground(this@AddCoinApplication.applicationContext)
            MainScope().launch(Dispatchers.IO) {
                val agreement = getAgreement()
                if (isbacg&&agreement){
                    BurialSiteRepostUtils.repostStart(this@AddCoinApplication)
                }
            }
        }
    }

    init {
        instance = this
    }

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks{
            override fun onActivityDestroyed(activity: Activity) {

            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {

            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

            }

            override fun onActivityResumed(activity: Activity) {
                activityDd = activity
            }

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

            }

            override fun onActivityStarted(activity: Activity) {

            }
        })
        MainScope().launch(Dispatchers.IO){
            DevicesUtils.initDevices(applicationContext)
            TaskStatusNet.initTaskStage(applicationContext)
        }
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
        gaid()
        //
//        FacebookSdk.setAutoInitEnabled(false)
//        FacebookSdk.setApplicationId()
//        FacebookSdk.fullyInitialize()
        //
        initFireBase()
        initAF("")
        initFaceBook(getString(R.string.facebook_app_id))
        time.start()
    }

    private fun initFireBase() {
        val remoteConfig = Firebase.remoteConfig
        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = 5499
        }
        remoteConfig.setConfigSettingsAsync(configSettings)
        url = remoteConfig.getString("url")
        remoteConfig.fetchAndActivate().addOnCompleteListener {
            if (it.isSuccessful) {
                url = remoteConfig.getString("url")
                val fbId = remoteConfig.getString("fb_id")
//                if (fbId.isNotEmpty()) {
//                    initFaceBook(fbId)
//                }

            }
        }
    }

    private fun initFaceBook(fbId: String) {
        FacebookSdk.setApplicationId(fbId)
//        FacebookSdk.setAutoInitEnabled(true)
//        FacebookSdk.fullyInitialize()
//        FacebookSdk.sdkInitialize(this) {
//            FacebookSdk.setAutoLogAppEventsEnabled(true)
//        }
    }

    private fun initAF(key: String) {
        AppsFlyerLib.getInstance().init(key, object : AppsFlyerConversionListener {
            override fun onConversionDataSuccess(p0: MutableMap<String, Any>?) {
            }

            override fun onConversionDataFail(p0: String?) {
            }

            override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {

            }

            override fun onAttributionFailure(p0: String?) {

            }
        }, this)
        AppsFlyerLib.getInstance().start(this, key, object : AppsFlyerRequestListener {
            override fun onSuccess() {
            }

            override fun onError(p0: Int, p1: String) {
            }
        })
        AppsFlyerLib.getInstance().setMinTimeBetweenSessions(0)
        AppsFlyerLib.getInstance().setDebugLog(BuildConfig.DEBUG)
    }

    fun gaid() {
        MainScope().launch (Dispatchers.IO){
            try {
                val deviceId = getDevicesId()
                if (!TextUtils.isEmpty(deviceId)){
                    gaid = deviceId
                }else{
                    val advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(this@AddCoinApplication)
                    gaid = advertisingIdInfo.id.toString()//
                    if (gaid<"0000000000"){
                        gaid = ""
                    }
                    if (!TextUtils.isEmpty(gaid)){
                        dataStore.saveDevicesId(gaid)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        //application生命周期监控
    }
}